<template>
  <ContentWrap>
    <div class="btnWrap routeHeader">
      <div>
        <el-button
          @click="submitData"
          v-hasPermi="['outsource:outbound-delivery-goods-detail:save']"
          type="primary"
          >提交</el-button
        >
        <el-button @click="close">关闭</el-button>
      </div>
    </div>
  </ContentWrap>
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="到货单号" prop="arriveNumber">
        <el-input v-model="queryParams.arriveNumber" clearable class="!w-240px" disabled />
      </el-form-item>
      <el-form-item label="签收人" prop="signer">
        <el-input v-model="queryParams.signer" clearable class="!w-240px" disabled />
      </el-form-item>
      <el-form-item label="到货日期" prop="arriveTime">
        <el-date-picker
          v-model="queryParams.arriveTime"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择日期"
          class="!w-220px"
        />
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%; height: 50px; display: flex; justify-content: space-between">
      <div>
        <el-button
          type="primary"
          @click="quoteArrival"
          :loading="exportLoading"
          v-hasPermi="['outsource:outbound-delivery-goods-detail:quote']"
        >
          引用到货
        </el-button>
      </div>
      <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
    </div>
    <el-table
      ref="multipleTableRef"
      border
      :summary-method="getSummaries"
      show-summary
      row-key="id"
      :height="tableHeight"
      :tree-props="{ children: 'children' }"
      default-expand-all
      v-loading="loading"
      :data="list"
    >
      <el-table-column label="序号" align="center" type="index" fixed="left" width="80" />
      <template v-for="(item, index) in tableTitleList">
        <el-table-column
          v-if="item.isTable && item.label != '序号'"
          :key="index"
          :type="item.type"
          :min-width="item.width"
          :header-align="item.headerAlign"
          :align="item.align"
          :label="item.label"
          :prop="item.field"
        >
          <template #default="scope">
            <template v-if="item.field === 'arriveQuantity'">
              <!-- 到货数量 -->
              <el-input
                v-nextInput="'arriveQuantity'"
                name="arriveQuantity"
                type="number"
                :min="0"
                v-model="scope.row.arriveQuantity"
              />
            </template>
            <template v-else>
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <span v-else>{{ scope.row[item.field] }}</span>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getList" />
  <!-- 引用到货 -->
  <OutboundDeliveryGoodsForm ref="outboundDeliveryGoodsFormRef" @success="rowData" />
</template>

<script setup lang="ts" name="OutboundDeliveryGoodsDetail">
import * as OutboundDeliveryGoodsDetailApi from '@/api/outsource/outsourceInAndOutStorage/outboundDeliveryGoodsDetail'
import { useTagsViewStore } from '@/store/modules/tagsView'
import OutboundDeliveryGoodsForm from './OutboundDeliveryGoodsForm.vue'
import { useUserStore } from '@/store/modules/user'
const message = useMessage()
const { push } = useRouter()
const tagsViewStore = useTagsViewStore()
const routes = useRouter() // 路由
const total = ref(0) // 列表的总页数
const list = ref<any[]>([]) // 列表的数据
const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
const multipleTableRef = ref()
const loading = ref(false) // 列表的加载中

const queryParams = reactive({
  arriveNumber: undefined,
  signer: undefined,
  arriveTime: undefined
})
//添加行
const rowData = (data) => {
  list.value = data.list
}
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const getSummaries = (param) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总计'
      return
    }
    if (['arriveQuantity'].includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    } else if (['purchaseQuantity'].includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    } else if (['quantityCollected'].includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    }
  })

  return sums
}
const getList = async () => {
  loading.value = true
  try {
    const data = await OutboundDeliveryGoodsDetailApi.getOutboundDeliveryGoodsDetailPage(
      queryParams
    )
    tableTitleList.value = data.labels
    total.value = data.total
    list.value = JSON.parse(route.query.list)
    loading.value = false
  } finally {
    loading.value = false
  }
}

/**打开表格表头设置**/
const tableTitleSet = ref()
const openTableTitleSet = () => {
  let code = 'OutboundDeliveryGoodsDetail'
  tableTitleSet.value.open(tableTitleList.value, code)
}
const outboundDeliveryGoodsFormRef = ref()
//引用到货
const quoteArrival = () => {
  outboundDeliveryGoodsFormRef.value.open(list.value)
}
//必填校验
const check = async () => {
  const data = await list.value
  for (let i = 0; i < data.length; i++) {
    if (
      data[i].arriveQuantity < 0 ||
      data[i].arriveQuantity > data[i].purchaseQuantity ||
      data[i].arriveQuantity == '' ||
      data[i].arriveQuantity == null ||
      data[i].arriveQuantity == undefined
    ) {
      message.warning('到货数量必须大于0且小于等于下单数量')
      return false
    }
  }
  if (!queryParams.arriveTime) {
    message.warning('到货日期不能为空')
    return false
  }
  return true
}
//提交
const submitData = async () => {
  let params = {
    signer: queryParams.signer,
    arriveTime: queryParams.arriveTime,
    outbounddeliverygoods: list.value
  }
  const isFlag = await check()
  if (isFlag) {
    loading.value = true
    await OutboundDeliveryGoodsDetailApi.createOutboundDeliveryGoodsDetail(params)
    message.success('创建成功')
    tagsViewStore.delView(routes.currentRoute.value)
    loading.value = false
    push('/outsource/outsource/warehousingOutbound/outboundDeliveryGoodsDetail')
  }
}
// 关闭

const close = () => {
  tagsViewStore.delView(routes.currentRoute.value)
  push('/outsource/outsource/warehousingOutbound/outboundDeliveryGoodsDetail')
}

/** 初始化 **/
const route = useRoute()
const tableHeight = ref(0)
onMounted(async () => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 210
  getList()
  //获取签收人
  queryParams.signer = useUserStore().getUser.nickname
})
</script>
